/**
 * 存储空间显示组件
 * Storage Usage Display Component
 */

class StorageComponent {
  constructor() {
    this.storageData = {
      used: 0,
      limit: 32212254720, // 30GB默认
      usagePercentage: 0,
      total_files: 0,
      total_size: 0
    };
    this.updateInterval = null;
    this.warningThreshold = 80; // 80%警告阈值
    this.criticalThreshold = 95; // 95%严重警告阈值
    this.init();
  }

  /**
   * 初始化存储组件
   */
  init() {
    this.bindEvents();
    this.loadStorageData();
    this.startAutoUpdate();
  }

  /**
   * 绑定事件
   */
  bindEvents() {
    // 监听文件上传完成事件
    document.addEventListener('fileUploaded', () => {
      this.loadStorageData();
    });

    // 监听文件删除事件
    document.addEventListener('fileDeleted', () => {
      this.loadStorageData();
    });

    // 点击存储详情
    const storageElements = document.querySelectorAll('[data-storage-detail]');
    storageElements.forEach(element => {
      element.addEventListener('click', () => {
        this.showStorageDetail();
      });
    });
  }

  /**
   * 加载存储数据
   */
  async loadStorageData() {
    try {
      const response = await api.get('/files/storage/stats');
      this.storageData = response.stats;
      this.updateDisplay();
      this.checkWarnings();
    } catch (error) {
      console.error('加载存储数据失败:', error);
      this.showError('加载存储数据失败');
    }
  }

  /**
   * 更新显示
   */
  updateDisplay() {
    this.updateTopBarStorage();
    this.updateSidebarStorage();
    this.updateDashboardCard();
    this.updateStorageProgress();
  }

  /**
   * 更新顶部栏存储显示
   */
  updateTopBarStorage() {
    const storageUsage = document.getElementById('storage-usage');
    if (storageUsage) {
      const usedText = this.formatBytes(this.storageData.used);
      const limitText = this.formatBytes(this.storageData.limit);
      storageUsage.textContent = `${usedText} / ${limitText}`;
      
      // 根据使用率改变颜色
      if (this.storageData.usagePercentage >= this.criticalThreshold) {
        storageUsage.className = 'text-sm text-red-600 font-medium';
      } else if (this.storageData.usagePercentage >= this.warningThreshold) {
        storageUsage.className = 'text-sm text-orange-600 font-medium';
      } else {
        storageUsage.className = 'text-sm text-neutral-600';
      }
    }
  }

  /**
   * 更新侧边栏存储显示
   */
  updateSidebarStorage() {
    const storageProgress = document.getElementById('storage-progress');
    const storageUsed = document.getElementById('storage-used');
    const storageTotal = document.getElementById('storage-total');

    if (storageProgress) {
      storageProgress.style.width = `${this.storageData.usagePercentage}%`;
      
      // 根据使用率改变进度条颜色
      let progressClass = 'bg-primary h-2 rounded-full transition-all duration-300';
      if (this.storageData.usagePercentage >= this.criticalThreshold) {
        progressClass = 'bg-red-500 h-2 rounded-full transition-all duration-300';
      } else if (this.storageData.usagePercentage >= this.warningThreshold) {
        progressClass = 'bg-orange-500 h-2 rounded-full transition-all duration-300';
      }
      storageProgress.className = progressClass;
    }

    if (storageUsed) {
      storageUsed.textContent = this.formatBytes(this.storageData.used);
    }

    if (storageTotal) {
      storageTotal.textContent = this.formatBytes(this.storageData.limit);
    }
  }

  /**
   * 更新仪表盘卡片
   */
  updateDashboardCard() {
    const storageUsageCard = document.getElementById('storage-usage-card');
    const storagePercentage = document.getElementById('storage-percentage');

    if (storageUsageCard) {
      storageUsageCard.textContent = this.formatBytes(this.storageData.used);
    }

    if (storagePercentage) {
      storagePercentage.textContent = `${this.storageData.usagePercentage}%`;
      
      // 根据使用率改变颜色
      if (this.storageData.usagePercentage >= this.criticalThreshold) {
        storagePercentage.className = 'text-red-600';
      } else if (this.storageData.usagePercentage >= this.warningThreshold) {
        storagePercentage.className = 'text-orange-600';
      } else {
        storagePercentage.className = 'text-green-600';
      }
    }
  }

  /**
   * 更新存储进度条
   */
  updateStorageProgress() {
    const progressBars = document.querySelectorAll('[data-storage-progress]');
    progressBars.forEach(bar => {
      const fill = bar.querySelector('.storage-fill');
      if (fill) {
        fill.style.width = `${this.storageData.usagePercentage}%`;
        
        // 动画效果
        fill.style.transition = 'width 0.5s ease-in-out';
      }
    });
  }

  /**
   * 检查警告
   */
  checkWarnings() {
    if (this.storageData.usagePercentage >= this.criticalThreshold) {
      this.showCriticalWarning();
    } else if (this.storageData.usagePercentage >= this.warningThreshold) {
      this.showWarning();
    }
  }

  /**
   * 显示警告
   */
  showWarning() {
    const message = `存储空间使用已达到 ${this.storageData.usagePercentage}%，建议清理不需要的文件`;
    notification.warning(message);
    
    // 在相关元素上添加警告样式
    this.addWarningStyles();
  }

  /**
   * 显示严重警告
   */
  showCriticalWarning() {
    const message = `存储空间严重不足！已使用 ${this.storageData.usagePercentage}%，请立即清理文件`;
    notification.error(message);
    
    // 在相关元素上添加严重警告样式
    this.addCriticalStyles();
  }

  /**
   * 添加警告样式
   */
  addWarningStyles() {
    const elements = document.querySelectorAll('[data-storage-warning]');
    elements.forEach(element => {
      element.classList.add('storage-warning');
    });
  }

  /**
   * 添加严重警告样式
   */
  addCriticalStyles() {
    const elements = document.querySelectorAll('[data-storage-warning]');
    elements.forEach(element => {
      element.classList.add('storage-critical');
    });
  }

  /**
   * 显示存储详情模态框
   */
  showStorageDetail() {
    const modal = this.createStorageDetailModal();
    document.body.appendChild(modal);
    
    // 显示模态框
    setTimeout(() => {
      modal.classList.remove('opacity-0');
      modal.classList.add('opacity-100');
    }, 10);
  }

  /**
   * 创建存储详情模态框
   */
  createStorageDetailModal() {
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 opacity-0 transition-opacity duration-300';
    modal.id = 'storage-detail-modal';
    
    modal.innerHTML = `
      <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 transform scale-95 transition-transform duration-300">
        <div class="p-6">
          <div class="flex items-center justify-between mb-4">
            <h3 class="text-lg font-semibold text-neutral-800">存储空间详情</h3>
            <button class="text-neutral-400 hover:text-neutral-600" onclick="this.closest('#storage-detail-modal').remove()">
              <i class="fa fa-times"></i>
            </button>
          </div>
          
          <div class="space-y-4">
            <!-- 总体使用情况 -->
            <div class="bg-neutral-50 rounded-lg p-4">
              <div class="flex items-center justify-between mb-2">
                <span class="text-sm font-medium text-neutral-600">总使用量</span>
                <span class="text-sm font-bold text-neutral-800">${this.formatBytes(this.storageData.used)} / ${this.formatBytes(this.storageData.limit)}</span>
              </div>
              <div class="w-full bg-neutral-200 rounded-full h-3 mb-2">
                <div class="h-3 rounded-full transition-all duration-500 ${this.getProgressBarColor()}" style="width: ${this.storageData.usagePercentage}%"></div>
              </div>
              <div class="text-center">
                <span class="text-lg font-bold ${this.getPercentageColor()}">${this.storageData.usagePercentage}%</span>
                <span class="text-sm text-neutral-500 ml-1">已使用</span>
              </div>
            </div>

            <!-- 文件统计 -->
            <div class="grid grid-cols-2 gap-4">
              <div class="text-center p-3 bg-blue-50 rounded-lg">
                <div class="text-2xl font-bold text-blue-600">${this.storageData.total_files || 0}</div>
                <div class="text-sm text-blue-600">文件总数</div>
              </div>
              <div class="text-center p-3 bg-green-50 rounded-lg">
                <div class="text-2xl font-bold text-green-600">${this.formatBytes(this.storageData.total_size || 0)}</div>
                <div class="text-sm text-green-600">文件大小</div>
              </div>
            </div>

            <!-- 存储建议 -->
            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
              <div class="flex items-start gap-2">
                <i class="fa fa-lightbulb-o text-yellow-600 mt-1"></i>
                <div>
                  <h4 class="font-medium text-yellow-800 mb-1">存储建议</h4>
                  <ul class="text-sm text-yellow-700 space-y-1">
                    ${this.getStorageTips().map(tip => `<li>• ${tip}</li>`).join('')}
                  </ul>
                </div>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="flex gap-2 pt-2">
              <button class="flex-1 bg-primary text-white py-2 px-4 rounded-md hover:bg-primary/90 transition-colors" onclick="this.closest('#storage-detail-modal').remove(); window.app.dashboard.switchView('files')">
                管理文件
              </button>
              <button class="flex-1 bg-neutral-200 text-neutral-700 py-2 px-4 rounded-md hover:bg-neutral-300 transition-colors" onclick="window.storageComponent.refreshStorageData()">
                刷新数据
              </button>
            </div>
          </div>
        </div>
      </div>
    `;

    // 点击背景关闭
    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        modal.remove();
      }
    });

    // 动画效果
    setTimeout(() => {
      const content = modal.querySelector('div > div');
      if (content) {
        content.classList.remove('scale-95');
        content.classList.add('scale-100');
      }
    }, 10);

    return modal;
  }

  /**
   * 获取进度条颜色类
   */
  getProgressBarColor() {
    if (this.storageData.usagePercentage >= this.criticalThreshold) {
      return 'bg-red-500';
    } else if (this.storageData.usagePercentage >= this.warningThreshold) {
      return 'bg-orange-500';
    } else {
      return 'bg-primary';
    }
  }

  /**
   * 获取百分比颜色类
   */
  getPercentageColor() {
    if (this.storageData.usagePercentage >= this.criticalThreshold) {
      return 'text-red-600';
    } else if (this.storageData.usagePercentage >= this.warningThreshold) {
      return 'text-orange-600';
    } else {
      return 'text-green-600';
    }
  }

  /**
   * 获取存储建议
   */
  getStorageTips() {
    const tips = [];
    
    if (this.storageData.usagePercentage >= this.criticalThreshold) {
      tips.push('立即删除不需要的大文件');
      tips.push('清理重复文件和旧版本');
      tips.push('考虑升级存储空间');
    } else if (this.storageData.usagePercentage >= this.warningThreshold) {
      tips.push('定期清理临时文件');
      tips.push('压缩大型文档和图片');
      tips.push('删除过期的文件');
    } else {
      tips.push('定期整理文件夹');
      tips.push('及时删除不需要的文件');
      tips.push('保持良好的文件管理习惯');
    }
    
    return tips;
  }

  /**
   * 格式化字节数
   */
  formatBytes(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  }

  /**
   * 开始自动更新
   */
  startAutoUpdate() {
    // 每5分钟更新一次存储数据
    this.updateInterval = setInterval(() => {
      this.loadStorageData();
    }, 5 * 60 * 1000);
  }

  /**
   * 停止自动更新
   */
  stopAutoUpdate() {
    if (this.updateInterval) {
      clearInterval(this.updateInterval);
      this.updateInterval = null;
    }
  }

  /**
   * 刷新存储数据
   */
  async refreshStorageData() {
    await this.loadStorageData();
    notification.success('存储数据已刷新');
  }

  /**
   * 显示错误
   */
  showError(message) {
    // 在存储相关元素上显示错误状态
    const storageElements = document.querySelectorAll('[data-storage-element]');
    storageElements.forEach(element => {
      element.textContent = '加载失败';
      element.classList.add('text-red-500');
    });
  }

  /**
   * 获取存储数据
   */
  getStorageData() {
    return { ...this.storageData };
  }

  /**
   * 设置警告阈值
   */
  setWarningThresholds(warning, critical) {
    this.warningThreshold = warning;
    this.criticalThreshold = critical;
    this.checkWarnings();
  }

  /**
   * 销毁组件
   */
  destroy() {
    this.stopAutoUpdate();
    
    // 移除事件监听器
    document.removeEventListener('fileUploaded', this.loadStorageData);
    document.removeEventListener('fileDeleted', this.loadStorageData);
  }
}

// 导出存储组件
window.StorageComponent = StorageComponent;